/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */
var dependsList = [
    'element', 'layer', 'form',
    'table', 'select2', 'zmnUtils', '$http',
    'zmnTable', 'formSelects', 'oms_purpose_modifier', 'zmnSearch', 'zmnSelect'
];

layui.extend({
    oms_purpose_modifier: 'purpose/list/zmn.oms.purpose.modifier'
}).define(dependsList, function(exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var zmnTable = layui.zmnTable;
    var formSelects = layui.formSelects;
    var element = layui.element;
    var $http = layui.$http;
    var zmnSelect = layui.zmnSelect;

    var tableConfig = layui.oms_purpose_modifier.tableConfig;
    var modifier = layui.oms_purpose_modifier.modifier;

    var tableInstance = null;
    // 当前操作的工单
    window.currentWork = {};

    var multipleSelectNameArray = [
        'channelIdList'
    ];

    function _openNewTab(url, text) {
        top.layui.index.openTabsPage(FICO_BASE_URL + url, text);
    }

    /**
     * 渲染表格
     * @param {object} params 查询参数
     * @param {array} data 表格数据
     * @returns {object}
     */
    var renderTable = (function($) {
        var defaultConfig = $.extend({
            id: 'zmn-work-table',
            elem: '#zmn-work-table',
            method: 'POST',
            contentType: 'application/json;charset=utf-8',
            limit: 100,
            limits: [100],
            cols: table.getConfig('zmn-work-table').cols,
            parseData: function(res) {
                var count = res.data ? res.data.count : 0;
                $('.layui-this').find('.count').text('（共 ' + count + ' 条）');

                return {
                    "code": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data ? (res.data.count > 10000 ? 10000 : res.data.count) : 0, //解析数据长度
                    "data": res.data ? res.data.data : [] //解析数据列表
                };
            },
            done: function(res, curr, count) {
                modifier.setDataList(res.data);
                modifier.initOperatePanel({}, function($elem) {
                    var orderId = $elem.data('order-id');
                    var workId = $elem.data('order-id');

                    var params = {
                        orderId: orderId,
                        workId: workId,
                    };

                    return params;
                });

                // initCompanyInfoHoverTips();
            }
        }, tableConfig.config);

        return function(params, data) {
            var where = { where: $.extend({}, tableConfig.orderObj, params) };
            var config = $.extend({}, defaultConfig, where, { data: data });

            return zmnTable.init({
                config: config,
                filter: 'zmn-work-table',

                event: function() {
                    table.on('tool(zmn-work-table)', function(rowObj) {
                        if (rowObj.event === 'operate') {
                            updateRowData(rowObj);
                        }
                    });

                    table.on('rowDouble(zmn-work-table)', function(rowObj) {
                        modifier.setCurrentDataByParams(rowObj.data);

                        // modifier.openHomeDialog(function () {
                        // });
                    });

                    // 监听头工具栏事件
                    table.on('toolbar(zmn-work-table)', function(obj) {});
                }
            });
        }

    })($);

    /**
     * 搜索框搜索方法
     * @param {object} params 查询参数
     */
    function searchForTable(params, data) {
        $('#tab-content').find('.layui-tab-item:first').removeClass('layui-show');
        tableInstance = renderTable(params, data);
    }

    /**
     * 获取工单信息
     * @param {object} params 查询参数
     * @param {function} cb 回调函数
     */
    function fetchWorkInfo(params) {
        return $http.$get(tableConfig.rowURL, params);
    }

    /**
     * 根据工单 id 更新行数据
     * @param workId
     */
    function updateRowDataByWorkId() {};

    window.updateRowDataByWorkId = updateRowDataByWorkId;

    /**
     * 更新表格单行数据
     * @param rowObj 表格数据行对象
     * @param data 行数据
     */
    function updateRowData(rowObj, data) {
        if (!rowObj) {
            return;
        }

        if (data) {
            rowObj.update(data);
            return;
        }

        fetchWorkInfo({ id: rowObj.data.workId }).done(function(info) {
            rowObj.update(info);
            rowObj.update(info);

            var $tr = $(rowObj.tr);

            $tr.css('backgroundColor', 'RGBA(0, 139, 125, .2)').siblings().css('backgroundColor', '');

            initWarningHoverTips($tr.find('.warning'));
            initAddressHoverTips($tr.find('.btn-address'));
            initRemarkHoverTips($tr.find('.btn-remark'));
        });
    }

    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams(field) {
        var params = {};

        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                if (multipleSelectNameArray.indexOf(key) !== -1) {
                    params[key] = field[key].split(',');
                } else {
                    params[key] = field[key];
                }
            }
        });

        return params;
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('blur', 'input', function() {
            var $this = $(this);
            $this.val($this.val().replace(/(^\s*)|(\s*$)/g, ''));
        });

        // 监听重置按钮点击
        $('#btn-clean').on('click', function() {
            setTimeout(function() {
                $('input:not([type="checkbox"][lay-filter="datepicker"])').val('');
                $('select').val('');

                var $multiSlectList = $('select[xm-select]');
                $multiSlectList.each(function() {
                    var xmSelect = $(this).attr('xm-select');
                    formSelects.value(xmSelect, []);
                });

                form.render('select');
            }, 100);
        });

        // 监听查询表单提交事件
        form.on('submit(submit-search)', function(obj) {
            var params = normalizeSearchParams(obj.field);
            let pageUrl = window.location.href;
            var filter_name = ''
            Object.keys(params).forEach((item, index) => {
                var fifname = $('[name^="' + item + '"]').parents('.layui-input-inline').eq($('[name^="' + item + '"]').parents('.layui-input-inline').length - 1).prev().text().split('：')[0]

                if (index != Object.keys(params).length - 1) {
                    filter_name = filter_name + fifname + '|'
                } else {
                    filter_name = filter_name + fifname
                }

            })

            try {
                if (filter_name.substring(filter_name.length - 1) == '|') {
                    filter_name = filter_name.substring(0, filter_name.length - 1)
                }
                console.log(filter_name)
                var data = {
                    employee_name: loginStaff.realName, // 内部员工姓名,
                    employee_id: loginStaff.staffId,
                    department_name: loginStaff.deptName, // 员工部门名称
                    department_id: loginStaff.deptId,
                    menu: path_name, //菜单目录路径名称
                    filter_name: filter_name,
                    tab_name: tabName || ''
                }
                webTrackingUtil('SYS_ADMIN_QUERY', pageUrl, 'click', 'SYS_ADMIN_QUERY_CLICK', data)
            } catch (error) {
                console.log(error)
            }

            searchForTable(params);
            return false;
        });

        // 监听查询表单导出事件
        form.on('submit(submit-export)', function(obj) {
            var params = normalizeSearchParams(obj.field);

            if (!tableConfig.exportURL) {
                layer.msg('请添加导出 URL');
                return false;
            }

            layer.tips('至多导出 5000 条', obj.elem, {
                success: function() {
                    setTimeout(function() {
                        layui.zmnUtils.exportFile(tableConfig.exportURL, params);
                    }, 300);
                }
            });

            return false;
        });

        element.on('tab(workListTabBrief)', function(obj) {
            var type = $(this).data('type');

            if (type === -1) {
                return;
            }

            renderTable({ tabType: type });
        });

        // 服务分类
        zmnSelect.selectServCategory('servCategId', {
            isRadio: true
        });
        // 渠道
        zmnSelect.searchChannel('channelIdList', {
            remote: {
                events: {
                    extendParams: function() {
                        return {
                            "rank": 2, //渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                        }
                    }
                }
            }
        });
    }

    /**
     * 初始化查询条件
     */
    function initQueryParams() {
        if (!defaultQuery) {
            return;
        }

        tableConfig.defaultParams = {};

        $('.tab-work-list .layui-tab-title li').removeClass('layui-this');

        // 用户id
        if (defaultQuery.userId) {
            tableConfig.defaultParams['userId'] = defaultQuery.userId;
            tableConfig.initialSearch = true;
        }

        // 会员id
        if (defaultQuery.memberId) {
            tableConfig.defaultParams['memberId'] = defaultQuery.memberId;
            tableConfig.initialSearch = true;
        }

        // 工单号
        if (defaultQuery.id) {
            tableConfig.defaultParams['code'] = defaultQuery.id;
            tableConfig.initialSearch = true;
        }
    }

    /**
     * 初始化页面
     */
    function initPage() {
        // 初始化查询条件
        initQueryParams();

        // 渲染 table
        if (tableConfig.initialSearch) {
            searchForTable(tableConfig.defaultParams);
        } else {
            searchForTable({}, []);
        }
    }

    /**
     * 初始化页面
     */
    function init() {
        // 初始化页面事件
        initEvent();

        // 初始化页面数据
        initPage();
    }

    init();
    exports('oms_purpose_list');
});